package com.wdl.modules.myhouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wdl.modules.myhouse.common.MyPage;
import com.wdl.modules.myhouse.dao.SysMenuDao;
import com.wdl.modules.myhouse.entity.sys.SysMenuEntity;
import com.wdl.modules.myhouse.entity.sys.SysRoleEntity;
import com.wdl.modules.myhouse.service.SysMenuService;
import com.wdl.modules.myhouse.utils.util.PageUtil;
import com.wdl.modules.myhouse.vo.MenuNodeVO;
import com.wdl.modules.myhouse.vo.SysMenuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜单表
 *
 * @author lucain sunlightcs@gmail.com
 * @since 1.0.0 2022-09-11
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuDao, SysMenuEntity> implements SysMenuService {

    @Autowired
    private SysMenuDao sysMenuDao;

    @Override
    public IPage<SysMenuEntity> getMenuByPage(MyPage mypage) {
        return this.baseMapper.selectPage(PageUtil.getIPage(mypage, new SysMenuEntity()), new QueryWrapper<>());
    }

    @Override
    public List<MenuNodeVO> buildMenuTree() {
        QueryWrapper<SysMenuEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().isNull(SysMenuEntity::getParentId);
        List<SysMenuEntity> roots = sysMenuDao.selectList(wrapper);
        ArrayList<MenuNodeVO> menuVOS = new ArrayList<>();
        if (roots != null) {
            for (SysMenuEntity root : roots) {
                MenuNodeVO vo = new MenuNodeVO();
                vo.setMenuName(root.getMenuName());
                vo.setId(root.getId());
                vo.setIcon(root.getIcon());
                vo.setChild(fillChildNodes(root));
                menuVOS.add(vo);
            }
        }
        return menuVOS;
    }


    private List<MenuNodeVO> fillChildNodes(SysMenuEntity root) {
        QueryWrapper<SysMenuEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysMenuEntity::getParentId, root.getId());
        List<SysMenuEntity> childs = sysMenuDao.selectList(wrapper);
        ArrayList<MenuNodeVO> menuVOS = new ArrayList<MenuNodeVO>();
        childs.forEach(child -> {
            MenuNodeVO nodeVO = new MenuNodeVO();
            nodeVO.setMenuName(child.getMenuName());
            nodeVO.setId(child.getId());
            nodeVO.setIcon(child.getIcon());
            fillChildNodes(child);
            menuVOS.add(nodeVO);
        });
        return menuVOS;
    }
}